package com.zjj.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.zjj.bean.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="用户管理")
public class UserController {

	static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

	@ApiOperation(value = "获取用户列表", notes = "用户列表")
	@GetMapping("/user")
	public List<User> list() {
		List<User> list = new ArrayList<User>(users.values());
		return list;
	}

	@ApiOperation(value = "获取用户信息", notes = "通过url的id，获取用户详细信息")
	@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path")
	@GetMapping("/user/{id}")
	public User userInfo(@PathVariable Integer id) {
		return users.get(id);
	}

	@ApiOperation(value = "创建用户", notes = "通过User对象创建用户")
	@ApiImplicitParam(name = "user", value = "用户信息对象", required = true, dataType = "User")
	@PostMapping("/user")
	public String addUser(@RequestBody User user) {
		users.put(user.getId(), user);
		return "success";
	}

	@ApiOperation(value = "修改用户", notes = "通过相关参数修改用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "用户编号", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "user", value = "用户信息对象", required = true, dataType = "User")
	})
	@PutMapping("/user/{id}")
	public String updateUser(@PathVariable Integer id, @RequestBody User user) {
		User u = users.get(id);
		u.setName(user.getName());
		u.setAge(user.getAge());
		users.put(id, u);
		return "success";
	}

	@ApiOperation(value = "删除用户", notes = "通过url的id，删除指定用户")
	@ApiImplicitParam(name = "id", value = "用户编号", required = true, dataType = "Integer", paramType = "path")
	@DeleteMapping("/user/{id}")
	public String deleteUser(@PathVariable Integer id) {
		users.remove(id);
		return "success";
	}
}
